package com.tanhua.dubbo.api.impl.mongo;

import com.tanhua.domain.mongo.Comment;
import com.tanhua.domain.vo.PageResult;
import com.tanhua.dubbo.api.mongo.MovementApi;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.ArrayList;
import java.util.List;

@Service
public class MovementApiImpl implements MovementApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public PageResult queryLikeUsers(Integer page, Integer pageSize, Long userId, Integer commentType) {
        Query query = new Query(Criteria.where("commentType").is(commentType));
        query.with(Sort.by(Sort.Order.desc("created")));
        List<Comment> commentList = mongoTemplate.find(query, Comment.class);
        List<Comment> result = new ArrayList<>();
        for (int count = 0; count < commentList.size(); count++) {
            Comment comment = commentList.get(count);
            if (mongoTemplate.exists(new Query(Criteria.where("publishId").is(comment.getPublishId())), "quanzi_album_" + userId)) {
                if ((count + 1 > ((page - 1) * pageSize)) && (count + 1 <= (page * pageSize))) {
                    result.add(comment);
                    if (count + 1 == (page * pageSize)) {
                        break;
                    }
                }
            }
        }
        return new PageResult(result.size(), pageSize, page, result);
    }
}
